package com.netty.demo.utils;

import com.netty.demo.protocol.packet.LoginRequestPacket;
import com.netty.demo.protocol.packet.MessagePacket;
import com.netty.demo.protocol.packet.PacketCodec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class LoginUtils {
    private static Map<String, Channel> loginChannelMap = new HashMap<>();


    public static AttributeKey<String> LOGIN = AttributeKey.newInstance("login");

    public static void markLogin(ChannelHandlerContext ctx, String userId){
        ctx.channel().attr(LOGIN).set(userId);
        System.out.println("当前用户ID：" + ctx.channel().attr(LOGIN).get());
    }

    public static boolean valid(LoginRequestPacket loginRequestPacket){
        return loginRequestPacket.getUsername().equals("zhangqiang") && loginRequestPacket.getPassword().equals("pwd");
    }

    public static void recordLogin(Channel channel, String userId){
        loginChannelMap.put(userId, channel);
    }

    public static void recordLoginout(Channel channel){
        loginChannelMap.remove(getLoginUserId(channel));
        channel.close();
    }

    public static boolean hasLogin(Channel channel){
        return channel.hasAttr(LOGIN);
    }

    public static String getLoginUserId(Channel channel){
        String userId = channel.attr(LOGIN).get();
        return userId;
    }

    public static Channel getLoginUserChannel(String userId){
        return loginChannelMap.get(userId.trim());
    }

    public static String createUserId(){
        String userId = String.valueOf(Math.round(Math.random() * 1000));
        if (loginChannelMap.keySet().contains(userId)) {
            return createUserId();
        } else {
            return userId;
        }
    }
}
